package com.cino.Thread;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {
    public static void main(String[] args) throws InterruptedException {
        int numberOfThreads = 3;
        CountDownLatch latch = new CountDownLatch(numberOfThreads);

        for (int i = 0; i < numberOfThreads; i++) {
            String threadName = "Worker-" + (i + 1);
            Thread thread = new Thread(new Worker(latch, threadName), threadName);
            thread.start();
        }

        // 主线程等待所有工作线程完成
        latch.await();
        System.out.println("所有工作线程已完成");
    }
}

class Worker implements Runnable {
    private final CountDownLatch latch;
    private final String threadName;

    public Worker(CountDownLatch latch, String threadName) {
        this.latch = latch;
        this.threadName = threadName;
    }

    @Override
    public void run() {
        try {
            // 设置线程名称
            Thread.currentThread().setName(threadName);
            System.out.println(Thread.currentThread().getName() + " 正在执行任务");
            Thread.sleep(1000); // 模拟任务执行时间
            System.out.println(Thread.currentThread().getName() + " 任务完成");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            latch.countDown(); // 任务完成后减少计数器
        }
    }
}